package ru.dirty.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AbsListView.OnScrollListener;

import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends Activity {
	
	protected LinearLayout downloadLayout;
	protected ListView list;
	protected ImageAndTextListAdapter adapter;
	protected Activity activity;
	protected View footerView;
	protected View errorfooterView;
	private Button popularButton;
	private Button newButton;
	private ImageButton refreshButton;
    private boolean popularOrNew = false;
	private Integer pages=2;
	public boolean changeUIFlag = true;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //make app without title
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);

        popularButton = (Button)this.findViewById(R.id.popularButton);
        newButton = (Button)this.findViewById(R.id.newButton);
  		refreshButton = (ImageButton)this.findViewById(R.id.refresh);
        downloadLayout = (LinearLayout)findViewById( R.id.linearLayout1 );
       // EditText filterText = (EditText) findViewById(R.id.search_box);
        //filterText.addTextChangedListener(filterTextWatcher);

      
        list = (ListView)findViewById(R.id.listView1);
 /*       ((PullToRefreshListView) list).setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh() {
                // Do work to refresh the list here.
               // new InitTask().execute();
            	new GetDataTask().execute();
            }
        });*/
        ArrayList<ImageAndText> dirtyNews = new ArrayList<ImageAndText>();
        activity = this;

        ViewGroup footerViewOriginal = (ViewGroup) findViewById(R.id.footer_layout);
        footerView = this.getLayoutInflater().inflate(R.layout.footer_layout,footerViewOriginal);
        footerViewOriginal = (ViewGroup) findViewById(R.id.error_footer_layout);
        errorfooterView = this.getLayoutInflater().inflate(R.layout.error_footer_layout,footerViewOriginal);
        Button connectionRepeat = (Button)errorfooterView.findViewById(R.id.repeatButton);

        list.addFooterView(footerView, null, false);

		adapter = new ImageAndTextListAdapter(this, dirtyNews, list);
	    list.setAdapter(adapter);

        EndlessScrollListener ls = new EndlessScrollListener();
        list.setOnScrollListener(ls);
        
        newButton.setOnClickListener(buttonListener);
        popularButton.setOnClickListener(buttonListener);
        refreshButton.setOnClickListener(buttonListener);
        connectionRepeat.setOnClickListener(buttonListener);
        
        
        list.setClickable(true);
        
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
            	Intent post = new Intent(getApplicationContext(), PostSelected.class);
            	post.putExtra("imgUrl", adapter.getItem(position).getImageUrl());
            	post.putExtra("header", adapter.getItem(position).getHeader().toString());
            	post.putExtra("text", adapter.getItem(position).getHtmlText());
            	post.putExtra("rating", adapter.getItem(position).getRating());
            	post.putExtra("autor", adapter.getItem(position).getAutor());
            	post.putExtra("stars", adapter.getItem(position).getStarsFlag());
            	post.putExtra("postID", adapter.getItem(position).getPostID());
            startActivity(post);
				
			}


          });
        
        InitTask initTask = new InitTask();
        changeUIFlag=true;
        SharedPreferences prefs = getSharedPreferences("dirty",MODE_PRIVATE);
        popularOrNew = prefs.getBoolean("bookmark",false);
        String url;
        if(popularOrNew){
            url = getString(R.string.currentUrlLast);
            setNewButtonSelected();
        }
        else{
            url = getString(R.string.currentUrlSpicy);
            setPopularButtonSelected();
        }

        initTask.execute(url);


    }
    
/*    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      setContentView(R.layout.main);
      //list = (ListView)findViewById(R.id.listView1);
     // this.setContentView(list);

      downloadLayout.setVisibility( View.GONE );
      list.setVisibility( View.VISIBLE );
		//ImageAndTextListAdapter adapter = new ImageAndTextListAdapter(this, dirtyNews, list);
       // list.setAdapter(adapter);
    }*/
    
    public class EndlessScrollListener implements OnScrollListener {
    	 
        private int visibleThreshold = 5;
        private int currentPage = 0;
        private int previousTotal = 1;
        private boolean loading = true;
     
        public EndlessScrollListener() {
        }
        public EndlessScrollListener(int visibleThreshold) {
            this.visibleThreshold = visibleThreshold;
        }
     
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
        	if(changeUIFlag)
        	{
                visibleThreshold = 5;
                currentPage = 0;
                previousTotal = 1;
                loading = true;
        	}
        		
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    currentPage++;
                }
            }

            if (!loading && (totalItemCount - visibleItemCount) <= 
            	(firstVisibleItem + visibleThreshold)) {
            	InitTask initTask = new InitTask(); 
            	Log.w("end of list","end");
            	synchronized(initTask)
            	{
            		
                	changeUIFlag = false;
	                initTask.execute(getString(R.string.dirtyPages));
	                loading = true;
            	}

            }
        }
     
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }


    }
    
    protected class InitTask extends AsyncTask<String, Integer, String>
    {
    	private final ArrayList<ImageAndText> data = new ArrayList<ImageAndText>();
    			@Override
    			protected void onPreExecute() 
                {
    				super.onPreExecute();
                    //Log.i( "dirty", "onPreExecute():");
                    if(changeUIFlag){
	                    downloadLayout.setVisibility( View.VISIBLE );
	                    list.setVisibility( View.GONE );
	                    if(adapter!=null)
	                    {
	                    	adapter.clear();
	                    	adapter.notifyDataSetChanged();
	                    }
	                    pages=2;
                    }
                    //Log.i( "dirty", "onPreExecute(): finish");
                }
                @Override
                protected String doInBackground( String... params ) 
                {
                	//Log.i( "dirty", "Background: start");
                	if(!changeUIFlag)
                	{
                		params[0]=params[0]+pages.toString();
                		pages++;
                	}
                try{
                	synchronized(this){
                	new DataParse(params[0],data);}
            		} catch (IOException e) {
            			// TODO Auto-generated catch block
            			e.printStackTrace();
            			return null;
            		}
                
                	//Log.i( "dirty", params[0]);
                    return "COMPLETE!";
                }
                
 
                @Override
                protected void onPostExecute(String result ) 
                {
                        super.onPostExecute(result);
                        //Log.i( "dirty", "onPostExecute: start");
                        if(result == null)
                        {
                        	if(!changeUIFlag)
                        	{
                        		//Log.w("result:","result = null");
                        		list.removeFooterView(footerView);
                                list.addFooterView(errorfooterView, null, false);
                                pages--;
                        	}
                        	else
                        	{
	                        	//Log.i( "dirty", "onPostExecute:result:"+result);
	                        	AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);//getBaseContext()); don't work for some reasons
	                        	builder.setMessage(getString(R.string.ConnectionProblem))
	                        	       .setCancelable(false)
	                        	       .setPositiveButton(getString(R.string.repeatButton), new DialogInterface.OnClickListener() {
	                        	           public void onClick(DialogInterface dialog, int id) {
	                        	        	  InitTask initTask = new InitTask();
	                            			  changeUIFlag = true;
	                	          		  	  initTask.execute(getString(R.string.currentUrlSpicy));
	                        	           }
	                        	       })
	                        	       .setNegativeButton(getString(R.string.cancelButton), new DialogInterface.OnClickListener() {
	                        	           public void onClick(DialogInterface dialog, int id) {
	                        	                dialog.cancel();
	                        	                MainActivity.this.finish();
	                        	           }
	                        	       });
	                        	AlertDialog alert = builder.create();
	                        	alert.setTitle("Ошибка");
	                        	alert.setIcon(android.R.drawable.ic_dialog_alert);
	                        	alert.show();
                        	}
                        }
                        else
                        {
	                       // Log.w("adapter count:",(Integer.toString(adapter.getCount()))); 
	                        int flag;
	            			if(!changeUIFlag)
	            			{
	            				//Log.w("changeUIFlag:","adding to adapter");
	            				int count=adapter.getCount();
		                        for(int i=0;i<data.size();i++)
		                        {
		                        	    flag=0;
		
		                        		for(int j=count-42;j<count;j++)
		                        		{
		                        				if(data.get(i).getPostID()!=adapter.getItem(j).getPostID())
		                        					flag++;
		                        		}
		                        		if(flag==42)
		                        		{
		                        			//Log.w("flag:","same items wasn't found, adding...");
		                        			adapter.add(data.get(i));
		                        		}
		                        }
	            			}
	            			else
		                        for(int i=0;i<data.size();i++)
		                        	adapter.add(data.get(i));
	
	                        adapter.notifyDataSetChanged();
	
	                        //Log.i( "dirty", "onPostExecute(): " + result );
	                        downloadLayout.setVisibility( View.GONE );
	                        if(changeUIFlag)
	                        	list.setSelection(0);
	                        list.setVisibility( View.VISIBLE );
	                        
                        }
                        
                }
    }
   /* private TextWatcher filterTextWatcher = new TextWatcher() {


        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            adapter.getFilter().filter(s);
        }

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			
		}

    };*/
    
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        SharedPreferences prefs = getSharedPreferences("dirty",MODE_PRIVATE);
        SharedPreferences.Editor edit = prefs.edit();
        edit.putBoolean("bookmark", popularOrNew);
        edit.commit();
        adapter.asyncImageLoader.stopThread();
        list.setAdapter(null);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.new_game:
        	startActivity(new Intent(this, AboutProgram.class));
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    private OnClickListener buttonListener = new OnClickListener() {
	    private InitTask initTask = new InitTask();
	    private boolean isPressed;
        private String currentUrl;
        public void onClick(View v) {
              if(popularOrNew){
                  isPressed = false;
                  currentUrl= getString(R.string.currentUrlLast);
              }
              else{
                  isPressed = true;
                  currentUrl= getString(R.string.currentUrlSpicy);
              }
          switch(v.getId())
          {
          	  case R.id.popularButton:
          		  if(!isPressed)
            		 if(initTask.getStatus()!=AsyncTask.Status.RUNNING){
            			initTask = new InitTask();
            			changeUIFlag = true;
                        popularOrNew = false;
            			currentUrl=getString(R.string.currentUrlSpicy);
                        setPopularButtonSelected();
	          		  	initTask.execute(currentUrl);
	          			isPressed = true;
            		 }
            	  break;
          	  case R.id.newButton:
          		  if(isPressed)
	         		 if(initTask.getStatus()!=AsyncTask.Status.RUNNING){
	         			initTask = new InitTask();
	                 	changeUIFlag = true;
	                 	currentUrl = getString(R.string.currentUrlLast);
                        popularOrNew = true;
                        setNewButtonSelected();
	          		  	initTask.execute(currentUrl);
	          			isPressed = false;
	           		 }
          	  case R.id.refresh:
          		if(initTask.getStatus()!=AsyncTask.Status.RUNNING)
          		{
	         		initTask = new InitTask();
	             	changeUIFlag = true;
	      		  	initTask.execute(currentUrl);
          		}
	         	break;
          	  case R.id.repeatButton:
          		    list.removeFooterView(errorfooterView);
                  	list.addFooterView(footerView, null, false);
	         		initTask = new InitTask();
	         		changeUIFlag = false;
	         		initTask.execute(getString(R.string.dirtyPages));
          }
        }
    };

    private void setNewButtonSelected(){
        newButton.setBackgroundResource(R.drawable.res);
        newButton.setTextColor(Color.parseColor(getString(R.color.white)));
        popularButton.setBackgroundResource(R.drawable.custom_button);
        popularButton.setTextColor(Color.parseColor(getString(R.color.blue2)));
    }

    private void setPopularButtonSelected(){
        popularButton.setBackgroundResource(R.drawable.res);
        popularButton.setTextColor(Color.parseColor(getString(R.color.white)));
        newButton.setBackgroundResource(R.drawable.custom_button);
        newButton.setTextColor(Color.parseColor(getString(R.color.blue2)));
    }

}